﻿using BadOCR.Runtime;
using Kyozy.MiniblinkNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BadOCR.UserControls
{
    /// <summary>
    /// SearchUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class SearchUserControl : UserControl
    {
        private WebView m_wke;
        public SearchUserControl()
        {
            InitializeComponent();

            DataContext = this;

            m_wke = new WebView(); //构造函数可以是无参，但是后面必须调用 Bind 方法
            m_wke.Bind(pictureBox);//随便绑定一个控件或窗口
            m_wke.LoadURL("https://www.baidu.com");
            //m_wke.OnLoadingFinish += M_wke_OnLoadingFinish;
        }

        //private void M_wke_OnLoadingFinish(object sender, LoadingFinishEventArgs e)
        //{
        //    // 每次加载url成功后都会触发
        //}

        /// <summary>
        /// 暂时这么处理,后期做成枚举description来优化
        /// </summary>
        public List<SearchMenuItem> MenuItems => new List<SearchMenuItem>()
        {
            new SearchMenuItem("baidu", "百度", "https://www.baidu.com/s?wd={text}"),
            new SearchMenuItem("bing", "必应", "https://cn.bing.com/search?q={text}"),
            new SearchMenuItem("toutiao", "头条", "https://so.toutiao.com/search?keyword={text}"),
            new SearchMenuItem("bilibili", "B站", "https://search.bilibili.com/all?keyword={text}"),

            new SearchMenuItem("sougou", "搜狗", "https://www.sogou.com/web?query={text}"),
            new SearchMenuItem("360", "360", "https://www.so.com/s?q={text}"),
            new SearchMenuItem("jingdong", "京东", "https://search.jd.com/Search?keyword={text}")
        };

        public byte SelectedMenuItemIndex { get; set; }

        public void Search(string text)
        {
            text = text.Replace("\r", "").Replace("\n", "");    // 搜索之前去掉所有的换行符

            if (textbox_searchContent.Text != text)
            {
                textbox_searchContent.Text = text;

                InternalSearch();
            }
        }

        private void listbox_menu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            InternalSearch();
        }

        private void textbox_searchContent_KeyDown(object sender, KeyEventArgs e)
        {
            InternalSearch();
        }

        private void InternalSearch()
        {
            var text = textbox_searchContent.Text;
            if (!string.IsNullOrEmpty(text))
            {
                var searchUrl = MenuItems[SelectedMenuItemIndex].Url.Replace("{text}", text);
                m_wke.LoadURL(searchUrl);
            }
        }
    }
}
